<template>
	<div class="app-container">
		<el-form :model="queryParams" class="queryForms" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
			<el-form-item label="任务单号" prop="repairNumber">
				<el-input maxlength="20" show-word-limit v-model="queryParams.repairNumber" placeholder="请输入任务单号"
					clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="产品名称" prop="productName">
				<el-input maxlength="20" show-word-limit v-model="queryParams.productName" placeholder="请输入产品名称"
					clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input maxlength="20" show-word-limit v-model="queryParams.productModel" placeholder="请输入产品型号"
					clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="产品编号" prop="productNumber">
				<el-input maxlength="20" show-word-limit v-model="queryParams.productNumber" placeholder="请输入产品编号"
					clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="审批状态" prop="repairApprovalStatus">
				<el-select v-model="queryParams.repairApprovalStatus">
					<el-option v-for="item in ApprovalStatusList" :key="item.id" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['erp:repair:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleSubmits"
					v-hasPermi="['erp:repair:submit']">提交</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleApprove({})"
					v-hasPermi="['erp:repair:approve']">审批</el-button>
			</el-col>
			<right-toolbar menuNames="repairs50" @changeTableData="changeTableData" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns" perm="erp:repair:list"></right-toolbar>
		</el-row>
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table :key="treetablekey" @expand-change="handleExpandChange" :row-class-name="row_class_name"
				@mousedown.native="mousedownTable" @row-click="row_click" @cell-mouse-enter="cell_mouse_enter"
				@cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable" @mouseleave.native="mouseupTable"
				ref="multipleTable" row-key="id" lazy :load="load" :default-expand-all="false"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-loading="loading"
				:data="repairList" @selection-change="handleSelectionChange" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					<template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
					</template>
				</el-table-column>
				<el-table-column label="返修任务单号" prop="repairNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="客户名称" prop="clientName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[1].visible" />
				<el-table-column label="客户代表" prop="productRepresentativeName" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[3].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="产品编号" prop="productNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[5].visible" />
				<el-table-column label="3B号" prop="bNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[6].visible" />
				<el-table-column label="审批状态" align="center" prop="repairApprovalStatus" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[7].visible">
					<template slot-scope="scope">
						<el-tag type="info"
							v-if="scope.row.repairApprovalStatus == '0' || scope.row.approvalStatus == '0'"
							class="disableClick">未提交</el-tag>
						<el-tag v-if="scope.row.repairApprovalStatus == '1' || scope.row.approvalStatus == '1'"
							@click="changeApprove(scope.row)" class="clickable">审批中</el-tag>
						<el-tag type="success"
							v-if="scope.row.repairApprovalStatus == '2' || scope.row.approvalStatus == '2'"
							@click="changeApprove(scope.row)" class="clickable">已通过</el-tag>
						<el-tag type="danger"
							v-if="scope.row.repairApprovalStatus == '3' || scope.row.approvalStatus == '3'"
							@click="changeApprove(scope.row)" class="clickable">未通过</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="产品接收时间" align="center" prop="receptionTime" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[8].visible">
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.receptionTime || scope.row.receiptTime, "{y}-{m}-{d}") }}</span>
					</template>
				</el-table-column>
				<!-- <el-table-column label="合同号/出库单" prop="contractNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[9].visible" /> -->
				<el-table-column label="监管协议号" prop="protocolNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[9].visible" />
				<!-- <el-table-column label="故障原因" prop="failureCause" min-width="150" :show-overflow-tooltip="true" v-if="columns[11].visible" /> -->

				<el-table-column label="返修单上传" align="center" prop="repairFileFlag" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[10].visible">
					<template slot-scope="scope">
						<div v-if="scope.row.repairFileFlag == 0">未上传</div>
						<div v-if="scope.row.repairFileFlag == 1">已上传</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" class-name="small-padding fixed-width" fixed="right" width="230">
					<template slot-scope="scope">
						<!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handlebacks(scope.row)" v-if="!scope.row.hasChildren && scope.row.retirementRepairlStatus == 0" v-hasPermi="['erp:repair:repaqirBack']">退修</el-button> -->
						<el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleSubmit(scope.row)"
							v-hasPermi="['erp:repair:submit']"
							v-if="(scope.row.hasChildren && scope.row.repairApprovalStatus == '0') || scope.row.approvalStatus == '0' || scope.row.repairApprovalStatus == '3' || scope.row.approvalStatus == '3'">提交</el-button>
						<el-button size="mini" type="text" icon="el-icon-s-order" @click="handleApprove(scope.row)"
							v-hasPermi="['erp:repair:approve']"
							v-if="(scope.row.repairApprovalStatus == '1' && scope.row.existApprovalStatus == '0') || (scope.row.approvalStatus == '1' && scope.row.existApprovalStatus == '0')">审批</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
							v-hasPermi="['erp:repair:remove']">删除</el-button>
						<el-button size="mini" type="text" icon="el-icon-folder" @click="handleAttachment(scope.row, 5)"
							v-if="!scope.row.hasChildren">附件</el-button>
						<el-dropdown size="mini" @command="command => handleCommand(command, scope.row)"
							v-hasPermi="['erp:repair:edit', 'erp:repair:detail', 'erp:repair:product', 'erp:repair:files']"
							v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="handleUpdate"
									v-hasPermi="['erp:repair:edit']">修改返修单</el-dropdown-item>
								<el-dropdown-item command="handleDetail"
									v-hasPermi="['erp:repair:detail']">返修单详情</el-dropdown-item>
								<el-dropdown-item command="handleProductList"
									v-hasPermi="['erp:repair:repairProduct']">返修单产品</el-dropdown-item>
								<el-dropdown-item command="handleAttachment"
									v-hasPermi="['erp:repair:files']">返修单附件</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination53" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改返修单对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="90%" append-to-body v-dialogDrag>
			<div style="max-height: 70vh; overflow-y: scroll; padding-right: 10px">
				<el-form ref="form" :model="form" :rules="rules" label-width="120px">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="返修任务单" prop="repairNumber">
								<el-input :disabled="isDisable" v-model="form.repairNumber" placeholder="请输入返修任务单"
									maxlength="20" show-word-limit />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="客户名称" prop="clientId">
								<el-select v-model="form.clientId" @change="selectClient" :disabled="isDisable"
									filterable>
									<el-option v-for="item in clientDatas" :key="item.id" :value="item.id"
										:label="item.clientName"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="客户代表" prop="productRepresentativeName">
								<el-input disabled v-model="form.productRepresentativeName" placeholder="请输入客户代表"
									maxlength="20" show-word-limit />
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="监管协议号" prop="protocolId">
								<el-select v-model="form.protocolId" @change="selectProtocol" :disabled="isDisable"
									filterable>
									<el-option v-for="item in tclientProtocol" :key="item.id"
										:label="item.protocolNumber" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="接收时间" prop="receptionTime">
								<el-date-picker :disabled="isDisable" clearable v-model="form.receptionTime" type="date"
									value-format="yyyy-MM-dd" placeholder="请选择接收时间"> </el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
					<div v-if="isDisable">
						<el-divider content-position="center">返修单产品</el-divider>
						<el-table :data="repairProductList" v-loading="productloading" border>
							<el-table-column label="序号" align="center" type="index" width="55" />
							<el-table-column label="产品名称" prop="productName" min-width="150"
								:show-overflow-tooltip="true" />
							<el-table-column label="产品型号" prop="productModel" min-width="150"
								:show-overflow-tooltip="true" />
							<el-table-column label="产品编号" prop="productNumber" min-width="150"
								:show-overflow-tooltip="true" />
							<el-table-column label="产品接收时间" align="center" prop="receiptTime" width="180"
								:show-overflow-tooltip="true" />
							<el-table-column label="产品数量" align="center" prop="productQuantity" min-width="100"
								:show-overflow-tooltip="true" />
							<el-table-column label="3B号" align="center" prop="bNumber" min-width="150"
								:show-overflow-tooltip="true" />
							<el-table-column label="合同号/出库单" align="center" prop="contractNumber" min-width="150"
								:show-overflow-tooltip="true" />
							<el-table-column label="故障模式" prop="failureMode" min-width="200"
								:show-overflow-tooltip="true" />
						</el-table>
						<pagination v-show="producttotal > 0" :total="producttotal" :page.sync="queryProduct.pageNum"
							:limit.sync="queryProduct.pageSize" @pagination="getlistRepairProduct" />
					</div>
				</el-form>
			</div>
			<div slot="footer" class="dialog-footer" v-if="!isDisable">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog title="审批" :visible.sync="openApprove" width="900px" append-to-body v-dialogDrag>
			<ApproveTemplete @cancelApprove="cancelApprove" :openApprove="openApprove"></ApproveTemplete>
		</el-dialog>

		<el-dialog title="审批流程" :visible.sync="openRecords" width="900px" append-to-body v-dialogDrag>
			<RecordsTemplete :approveRecord="approveRecord"></RecordsTemplete>
		</el-dialog>
	</div>
</template>

<script>
import DocumentShow from "@/views/components/DocumentShow"
import { listRepairProduct, delRepairProduct } from "@/api/repair/repairProduct"
import { retirementRepair, approvalRecord, approverRepair, listRepair, getRepair, delRepair, addRepair, updateRepair, submitRepair, submitRepairProduct } from "@/api/repair/repair"
import { clientList, getcolumn } from "@/api/selectList"
import { getClient } from "@/api/system/custom"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { mapGetters } from "vuex"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'    
export default {
	name: "Repair_menu",
	components: { ApproveTemplete, RecordsTemplete, DocumentShow },
	computed: {
		...mapGetters(["sidebar"])
	},
	mixins: [searchStateMixin],  
	data() {
		return {
			tableTreeRefreshTool: {}, // 用于存储 resolve 方法和展开状态
			ApprovalStatusList: [
				{
					id: "0",
					name: "未提交"
				},
				{
					id: "1",
					name: "审批中"
				},
				{
					id: "2",
					name: "已通过"
				},
				{
					id: "3",
					name: "未通过"
				}
			],
			loadingChild: false, // 加载状态
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			rows: [],
			fileVedioList: [],
			showfileListDialog: false,
			showTodoListDialog: false,
			eleTabTop: 0, //表格容器距浏览器顶部距离
			treetablekey: Math.random(),
			openRecords: false,
			// 审批流程记录
			approveRecord: {},
			productloading: false,
			repairProductList: [],
			producttotal: 0,
			queryProduct: { pageNum: 1, pageSize: 10 },
			// 区分新增  查看按钮
			isDisable: false,
			// 审批数据
			approveForm: {},
			openApprove: false,
			maps: new Map(),
			// 监管协议号
			tclientProtocol: [],
			// 客户列表
			clientDatas: [],
			// 是否展开，默认全部展开
			isExpandAll: true,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 子表选中数据
			checkedTRepairProduct: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 返修单表格数据
			repairList: [],
			// 返修单产品列表格数据
			tRepairProductList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				repairNumber: null,
				clientId: null,
				clientName: null,
				productRepresentativeId: null,
				productRepresentativeName: null,
				contractNumber: null,
				protocolId: null,
				protocolNumber: null,
				receptionTime: null,
				failureCause: null,
				bNumber: null,
				programBeginTime: null,
				programFinishTime: null,
				repairApprovalStatus: null,
				productName: null,
				productModel: null,
				productNumber: null
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				repairNumber: [{ required: true, message: "返修任务单不能为空", trigger: "blur" }],
				// contractNumber: [{ required: true, message: "合同号不能为空", trigger: "blur" }],
				protocolId: [{ required: true, message: "监管协议号不能为空", trigger: "blur" }],
				receptionTime: [{ required: true, message: "接收时间不能为空", trigger: "blur" }],
				clientId: [{ required: true, message: "客户名称不能为空", trigger: "blur" }]
			},
			repairIds: "",
			// 列信息
			columns: [
				{ key: 0, label: `返修任务单号`, visible: true },
				{ key: 1, label: `客户名称`, visible: true },
				{ key: 2, label: `客户代表`, visible: true },
				{ key: 3, label: `产品名称`, visible: true },
				{ key: 4, label: `产品型号`, visible: true },
				{ key: 5, label: `产品编号`, visible: true },
				{ key: 6, label: `3B号`, visible: true },
				{ key: 7, label: `审批状态`, visible: true },
				{ key: 8, label: `产品接收时间`, visible: true },
				{ key: 9, label: `监管协议号`, visible: true },
				{ key: 10, label: `返修单上传`, visible: true }
			],
			pageSize: 10
		}
	},
	created() {
		// 如果是页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			this.resetForm("queryForm")
			// 清除URL中的查询参数（不刷新页面）
			window.history.replaceState({}, document.title, window.location.pathname);
		}
		// this.getSize()
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				if (newQuery.queryData) {
					if (Object.keys(newQuery.queryData).length === 0) {
						this.resetQuerys()
						// this.getSize()
					} else {
						this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
						// this.getSize()
					}
				} this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination53" }).then(response => {
				this.pageSize = this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		// 审批流程
		changeApprove(row) {
			if (row.repairApprovalStatus == "0" || row.approvalStatus == "0") {
				return false
			}
			approvalRecord({
				id: row.hasChildren ? row.id : row.id.substring(3),
				workflowType: row.hasChildren ? "2" : "3"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},
		// 审批
		handleApprove(row) {
			if (row.id) {
				this.approveForm = {
					id: row.hasChildren ? row.id : row.id.substring(3),
					status: row.hasChildren ? true : false,
					repairId: row.repairId
				}
				this.openApprove = true
			} else {
				this.approveForm = {}
				let checkp = this.rows.every(item => {
					return typeof item.id == "number"
				})
				if (!checkp) {
					this.$modal.msg("只能选择父级产品进行审批")
					return false
				}
				this.openApprove = true
			}
		},
		cancelApprove(data) {
			if (data.flag) {
				const _this = this
				let params = {
					approvalStatus: data.approvalStatus,
					causeRejection: data.causeRejection,
					workflowType: _this.approveForm.status ? (_this.approveForm.status ? "2" : "3") : "2"
				}
				_this.approveForm.id ? (params.id = _this.approveForm.id) : (params.ids = this.ids)
				this.$modal
					.confirm(`是否确认审批数据？`)
					.then(function () {
						return approverRepair(params)
					})
					.then(() => {
						_this.approveForm.status ? (_this.approveForm.status ? _this.getList() : _this.refreshLoadTree(_this.approveForm.repairId)) : _this.getList()
						_this.$modal.msgSuccess("审批成功")
						localStorage.setItem("todoMessage", "repair_menu3")
						_this.$refs.multipleTable.clearSelection()
					})
					.catch(() => { })
			}
			this.openApprove = false
		},
		handleSubmits() {
			let checkp = this.rows.every(item => {
				return typeof item.id == "number"
			})
			if (!checkp) {
				this.$modal.msg("只能选择父级产品进行提交")
				return false
			}
			const _this = this
			this.$modal
				.confirm(`是否确认提交数据？`)
				.then(function () {
					return submitRepair({
						workIds: _this.ids,
						workflowType: "2"
					})
				})
				.then(() => {
					_this.closeAllExpansions()
					localStorage.setItem("todoMessage", "repair_menu1")
					_this.$modal.msgSuccess("提交成功")
					_this.$refs.multipleTable.clearSelection()
				})
				.catch(() => { })
		},
		// 提交
		handleSubmit(row) {
			if (row.hasChildren) {
				this.editStatus("editRepair", row.id, row.repairApprovalStatus || row.approvalStatus)
			} else {
				this.editStatus("editRepairProduct", row.id.substring(3), row.repairApprovalStatus || row.approvalStatus, row.repairId)
			}
		},
		editStatus(type, id, status, parentId) {
			const _this = this
			let params = {
				submitStatus: status == "0" ? "1" : status == "3" ? "2" : "",
				workId: id,
				workflowType: type == "editRepair" ? "2" : "3"
			}
			this.$modal
				.confirm(`是否确认提交${type == "editRepair" ? "返修单" : "返修单产品"}数据项？`)
				.then(function () {
					return type == "editRepair" ? submitRepair(params) : submitRepairProduct(params)
				})
				.then(() => {
					type == "editRepair" ? _this.getList() : _this.refreshLoadTree(parentId)
					_this.$modal.msgSuccess("提交成功")
					this.$refs.multipleTable.clearSelection()
					localStorage.setItem("todoMessage", "repair_menu5")
				})
				.catch(() => { })
		},
		// 展开/收起时触发
		handleExpandChange(row, expanded) {
			const curr = this.tableTreeRefreshTool[row.id]
			if (!curr) return
			curr.expandCount++
			if (expanded && curr.expandCount > 1 && !curr.prevStatus) {
				let queryParams = JSON.parse(JSON.stringify(this.queryParams))
				delete queryParams.pageSize
				delete queryParams.pageNum
				listRepairProduct({
					repairId: row.id,
					...queryParams
				}).then(res => {
					if (res.rows.length > 0) {
						res.rows.forEach((item, index) => {
							// 父子id会冲突
							item.id = "c" + item.id
							item.sort = index + 1
						})
						curr.resolve(res.rows)
					} else {
						curr.resolve([])
					}
				})
			}
			curr.prevStatus = expanded
		},
		//懒加载
		async load(tree, treeNode, resolve) {
			if (!this.maps.has(tree.id)) {
				this.maps.set(tree.id, { tree: tree, treeNode, resolve })
			}
			this.tableTreeRefreshTool[tree.id] = {
				resolve,
				expandCount: 0, // 展开次数
				prevStatus: false // 上一次的展开状态
			}
			let _this = this
			let queryParams = JSON.parse(JSON.stringify(this.queryParams))
			delete queryParams.pageSize
			delete queryParams.pageNum
			let form = {
				repairId: tree.id,
				...queryParams
			}
			let result = await listRepairProduct(form)
			console.log(result.rows.length, "result.rows.length")
			if (result.rows.length != 0) {
				result.rows.forEach((item, index) => {
					item.id = "son" + item.id
					item.sort = index + 1
				})

				tree.children = result.rows
				resolve(result.rows)
			} else {
				resolve([])
			}
		},
		// 更多操作触发
		handleCommand(command, row) {
			switch (command) {
				case "handleProductList":
					this.handleProductList(row)
					break
				case "handleUpdate":
					this.handleUpdate(row)
					break
				case "handleDetail":
					this.handleDetail(row)
					break
				case "handleAttachment":
					this.handleAttachment(row, 4)
					break
				default:
					break
			}
		},
		handleDetail(row) {
			this.repairIds = row.id
			this.reset()
			this.isDisable = true
			this.title = "查看详情"
			this.getrepairDetail(row.id)
			this.getlistRepairProduct(row.id)
		},
		getlistRepairProduct(id) {
			this.productloading = true
			this.queryProduct.repairId = this.repairIds
			listRepairProduct(this.queryProduct).then(response => {
				this.repairProductList = response.rows
				this.producttotal = response.total
				this.productloading = false
			})
		},
		handleProductList(row) {
			this.$router.push({
				path: "/repair/repairProduct/repairProduct/index",
				query: {
					id: row.id,
					receptionTime: row.receptionTime,
					// queryParams: JSON.stringify(this.queryParams)
				}
			})
		},
		selectProtocol(e) {
			this.form.protocolNumber = this.tclientProtocol.filter(item => item.id == e).map(items => items.protocolNumber)[0]
		},
		selectClient(e) {
			this.clientDatas.forEach(item => {
				if (e == item.id) {
					this.form.clientName = item.clientName
					this.form.productRepresentativeName = item.clientType
					this.form.protocolId = undefined
					this.getClientData(e)
				}
			})
		},
		getClientData(e) {
			getClient(e).then(response => {
				if (response.data.tclientProtocolList && response.data.tclientProtocolList.length > 0) {
					this.tclientProtocol = response.data.tclientProtocolList.filter(item => item.state == "1")
					if (this.tclientProtocol.length == 1) {
						this.form.protocolId = this.tclientProtocol[0].id
						this.form.protocolNumber = this.tclientProtocol[0].protocolNumber
					}
				}
			})
		},
		refreshLoadTree(parentId) {
			const { tree, treeNode, resolve } = this.maps.get(parentId)
			this.load(tree, treeNode, resolve) // 重新加载子级数据
			this.$refs.multipleTable.clearSelection()
		},
		// 关闭所有展开的行
		closeAllExpansions() {
			this.repairList.forEach(row => {
				this.$refs.multipleTable.toggleRowExpansion(row, false)
			})
			this.$refs.multipleTable.clearSelection()
			this.getList()
		},
		/** 查询返修单列表 */
		getList() {
			this.loading = true
			listRepair(this.queryParams).then(response => {
				this.repairList = response.rows
				this.repairList.forEach((item, index) => {
					item.hasChildren = true //树结构hasChildren
					item.sort = index + 1
				})
				this.total = response.total
				this.loading = false
			})
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				repairNumber: null,
				clientId: null,
				clientName: null,
				productRepresentativeId: null,
				productRepresentativeName: null,
				contractNumber: null,
				protocolId: null,
				protocolNumber: null,
				receptionTime: null,
				failureCause: null,
				bNumber: null,
				programBeginTime: null,
				programFinishTime: null,
				repairApprovalStatus: null,
				remark: null,
				productName: null,
				productModel: null,
				productNumber: null
			}
			this.tRepairProductList = []
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.saveSearchState()   
			this.getList()
			this.treetablekey = Math.random()
		},
		resetQuerys() {
			this.queryParams = {
				pageNum: 1,
				pageSize: this.pageSize,
				repairNumber: null,
				clientId: null,
				clientName: null,
				productRepresentativeId: null,
				productRepresentativeName: null,
				contractNumber: null,
				protocolId: null,
				protocolNumber: null,
				receptionTime: null,
				failureCause: null,
				bNumber: null,
				programBeginTime: null,
				programFinishTime: null,
				repairApprovalStatus: null,
				productName: null,
				productModel: null,
				productNumber: null
			}
			this.resetForm("queryForm")
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.queryParams = {
				pageNum: 1,
				pageSize: this.pageSize,
				repairNumber: null,
				clientId: null,
				clientName: null,
				productRepresentativeId: null,
				productRepresentativeName: null,
				contractNumber: null,
				protocolId: null,
				protocolNumber: null,
				receptionTime: null,
				failureCause: null,
				bNumber: null,
				programBeginTime: null,
				programFinishTime: null,
				repairApprovalStatus: null,
				productName: null,
				productModel: null,
				productNumber: null
			}
			this.resetForm("queryForm")
			this.clearSearchCache() 
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.multipleTable.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			// this.currentEnterRow || this.$refs.table.toggleRowSelection(row)
			console.log(row)
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.multipleTable.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.multipleTable.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.multipleTable.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		getclientList() {
			clientList({
				clientState: "1"
			}).then(res => {
				this.clientDatas = res.rows
			})
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.isDisable = false
			this.reset()
			this.getclientList()
			this.open = true
			this.title = "添加返修单"
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			this.isDisable = false
			this.title = "修改返修单"
			this.getrepairDetail(row.id)
		},
		getrepairDetail(id) {
			getRepair(id).then(response => {
				this.form = response.data
				this.getclientList()
				this.getClientData(this.form.clientId)
				// this.tRepairProductList = response.data.tRepairProductList
				this.open = true
			})
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					// this.form.tRepairProductList = this.tRepairProductList
					if (this.form.id != null) {
						updateRepair(this.form).then(response => {
							this.$modal.msgSuccess("修改成功")
							this.open = false
							this.getList()
						})
					} else {
						addRepair(this.form).then(response => {
							this.$modal.msgSuccess("新增成功")
							this.open = false
							this.getList()
						})
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const _this = this
			if (row.hasChildren) {
				_this.deleteData("delRepair", row.id)
			} else {
				this.deleteData("delRepairProduct", row.id.substring(3), row.repairId)
			}
		},
		// refreshLoadTree(parentId) {
		// 	// 根据父级id取出对应节点数据
		// 	const { tree, treeNode, resolve } = this.maps.get(parentId)
		// 	this.$set(this.$refs.multipleTable.store.states.lazyTreeNodeMap, parentId, [])
		// 	if (tree) {
		// 		// 将取出对应数据再传给load方法
		// 		this.load(tree, treeNode, resolve)
		// 	}
		// },
		deleteData(type, id, parentId) {
			const _this = this
			this.$modal
				.confirm(`是否确认删除${type == "delRepair" ? "返修单" : "返修单产品"}数据项？`)
				.then(function () {
					return type == "delRepair" ? delRepair(id) : delRepairProduct(id)
				})
				.then(() => {
					type == "delRepair" ? _this.getList() : _this.refreshLoadTree(parentId)
					_this.$modal.msgSuccess("删除成功")
					this.$refs.multipleTable.clearSelection()
				})
				.catch(() => { })
		},
		/** 返修单产品列序号 */
		rowTRepairProductIndex({ row, rowIndex }) {
			row.index = rowIndex + 1
		},
		/** 返修单产品列添加按钮操作 */
		handleAddTRepairProduct() {
			let obj = {}
			obj.productId = ""
			obj.productName = ""
			obj.productModel = ""
			obj.productNumber = ""
			obj.receiptTime = ""
			obj.approvalStatus = ""
			obj.planFlag = ""
			obj.remark = ""
			this.tRepairProductList.push(obj)
		},
		/** 返修单产品列删除按钮操作 */
		handleDeleteTRepairProduct() {
			if (this.checkedTRepairProduct.length == 0) {
				this.$modal.msgError("请先选择要删除的返修单产品列数据")
			} else {
				const tRepairProductList = this.tRepairProductList
				const checkedTRepairProduct = this.checkedTRepairProduct
				this.tRepairProductList = tRepairProductList.filter(function (item) {
					return checkedTRepairProduct.indexOf(item.index) == -1
				})
			}
		},
		/** 复选框选中数据 */
		handleTRepairProductSelectionChange(selection) {
			this.checkedTRepairProduct = selection.map(item => item.index)
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"erp/repair/export",
				{
					...this.queryParams
				},
				`repair_${new Date().getTime()}.xlsx`
			)
		},
		handleAttachment(row, status) {
			// 5  子附件       4 父
			let ids = status == 5 ? row.id.substring(3) : row.id
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: ids,
					typeId: status,
					perm: "erp:repair:files",
					repairNumber: row.repairNumber,
					productName: row.productName,
					productModel: row.productModel,
					// queryParams: JSON.stringify(this.queryParams),
					paths: "/repair/repair_menu",
					show: true
				}
			})
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 230px !important;
}
</style>
